import React, { useState, useEffect } from 'react';
import { Grade, studentOptions, subjectOptions, examTypeOptions, termOptions, validateGrade, getScoreLevelText } from '../types';

interface AddEditGradeModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: (grade: Grade) => void;
  initialData?: Grade | null;
  isEditing: boolean;
  termOptions: { value: string; label: string }[];
  examTypeOptions: { value: string; label: string }[];
  studentOptions: { value: string; label: string; classId: string; academy: string }[];
  subjectOptions: { value: string; label: string; maxScore: number }[];
  academyOptions: { value: string; label: string }[];
  classOptions: { value: string; label: string }[];
  instructorOptions: { value: string; label: string }[];
  lecturerOptions: { value: string; label: string }[];
  teachingMonthOptions: { value: string; label: string }[];
  onClassChange: (className: string) => void;
}

const AddEditGradeModal: React.FC<AddEditGradeModalProps> = ({
  isOpen,
  onClose,
  onSave,
  initialData,
  isEditing,
  termOptions,
  examTypeOptions,
  studentOptions,
  subjectOptions,
  academyOptions,
  classOptions,
  instructorOptions,
  lecturerOptions,
  teachingMonthOptions,
  onClassChange
}) => {
  const [formData, setFormData] = useState<Omit<Grade, 'id'>>({
    term: '',
    examType: '',
    studentId: '',
    studentName: '',
    subject: '',
    score: 0,
    remark: '',
    createdBy: localStorage.getItem('currentUser') || 'system',
    createdAt: new Date().toISOString(),
    updatedBy: localStorage.getItem('currentUser') || 'system',
    updatedAt: new Date().toISOString(),
    academy: '',
    className: '',
    instructor: '',
    lecturer: '',
    teachingMonth: '',
    totalStudents: 0,
  });

  const [errors, setErrors] = useState<{ [key: string]: string }>({});

  // 初始化表单数据
  useEffect(() => {
    if (isOpen) {
      if (isEditing && initialData) {
        setFormData({
          term: initialData.term,
          examType: initialData.examType,
          studentId: initialData.studentId,
          studentName: initialData.studentName,
          subject: initialData.subject,
          score: initialData.score,
          remark: initialData.remark || '',
          createdBy: initialData.createdBy || localStorage.getItem('currentUser') || 'system',
          createdAt: initialData.createdAt || new Date().toISOString(),
          updatedBy: localStorage.getItem('currentUser') || 'system',
          updatedAt: new Date().toISOString(),
          academy: initialData.academy || '',
          className: initialData.className || '',
          instructor: initialData.instructor || '',
          lecturer: initialData.lecturer || '',
          teachingMonth: initialData.teachingMonth || '',
          totalStudents: initialData.totalStudents || 0,
        });
      } else {
        // 设置默认值
        setFormData({
          term: termOptions[0]?.value || '',
          examType: examTypeOptions[0]?.value || '',
          studentId: '',
          studentName: '',
          subject: '',
          score: 0,
          remark: '',
          createdBy: localStorage.getItem('currentUser') || 'system',
          createdAt: new Date().toISOString(),
          updatedBy: localStorage.getItem('currentUser') || 'system',
          updatedAt: new Date().toISOString(),
          academy: academyOptions[0]?.value || '',
          className: classOptions[0]?.value || '',
          instructor: instructorOptions[0]?.value || '',
          lecturer: lecturerOptions[0]?.value || '',
          teachingMonth: teachingMonthOptions[0]?.value || '',
          totalStudents: 0,
        });
      }
      setErrors({});
    }
  }, [isOpen, isEditing, initialData]);

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    
    // 特殊处理分数输入，确保是数字
    if (name === 'score') {
      const numValue = value === '' ? 0 : parseFloat(value);
      setFormData(prev => ({
        ...prev,
        [name]: isNaN(numValue) ? 0 : numValue,
      }));
    } else {
      setFormData(prev => ({
        ...prev,
        [name]: value,
      }));
      
      // 当班级选择改变时，调用父组件的onClassChange函数
      if (name === 'className') {
        onClassChange(value);
      }
    }

    // 当学生ID改变时，自动更新学生姓名
    if (name === 'studentId') {
      const selectedStudent = studentOptions.find(student => student.value === value);
      if (selectedStudent) {
        setFormData(prev => ({
          ...prev,
          studentName: selectedStudent.label,
        }));
      } else {
        setFormData(prev => ({
          ...prev,
          studentName: '',
        }));
      }
    }

    // 清除该字段的错误
    if (errors[name]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  // 自动生成备注（基于分数等级）
  const autoGenerateRemark = (score: number, subject: string) => {
    if (score > 0 && subject) {
      const levelText = getScoreLevelText(score, subject);
      return levelText;
    }
    return '';
  };

  // 处理保存操作
  const handleSave = () => {
    // 自动生成备注
    const autoRemark = autoGenerateRemark(formData.score, formData.subject);
    const finalFormData = { ...formData, remark: autoRemark };
    
    // 验证表单数据
    const validation = validateGrade(finalFormData);
    
    if (!validation.isValid) {
      // 转换错误数组为对象，便于在表单中显示
      const errorObj: { [key: string]: string } = {};
      validation.errors.forEach(error => {
        if (error.includes('教学周期')) errorObj.term = error;
        if (error.includes('类型')) errorObj.examType = error;
        if (error.includes('学院')) errorObj.academy = error;
        if (error.includes('班级')) errorObj.className = error;
        if (error.includes('导员')) errorObj.instructor = error;
        if (error.includes('讲师')) errorObj.lecturer = error;
        if (error.includes('教学月度')) errorObj.teachingMonth = error;
        if (error.includes('总人数')) errorObj.totalStudents = error;
        if (error.includes('学生')) errorObj.studentId = error;
        if (error.includes('课程')) errorObj.subject = error;
        if (error.includes('分数')) errorObj.score = error;
      });
      setErrors(errorObj);
      return;
    }

    // 创建成绩记录对象，包含唯一ID
    const grade: Grade = {
      ...finalFormData,
      id: isEditing && initialData ? initialData.id : `grade-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
    };

    // 调用保存回调
    onSave(grade);
    
    // 重置表单
    setFormData({
      term: termOptions[0]?.value || '',
      examType: examTypeOptions[0]?.value || '',
      studentId: '',
      studentName: '',
      subject: '',
      score: 0,
      remark: '',
      createdBy: localStorage.getItem('currentUser') || 'system',
      createdAt: new Date().toISOString(),
      updatedBy: localStorage.getItem('currentUser') || 'system',
      updatedAt: new Date().toISOString(),
      academy: academyOptions[0]?.value || '',
      className: classOptions[0]?.value || '',
      instructor: instructorOptions[0]?.value || '',
      lecturer: lecturerOptions[0]?.value || '',
      teachingMonth: teachingMonthOptions[0]?.value || '',
      totalStudents: 0,
    });
    setErrors({});
  };

  // 处理模态框关闭
  const handleClose = () => {
    setFormData({
      term: termOptions[0]?.value || '',
      examType: examTypeOptions[0]?.value || '',
      studentId: '',
      studentName: '',
      subject: '',
      score: 0,
      remark: '',
      createdBy: localStorage.getItem('currentUser') || 'system',
      createdAt: new Date().toISOString(),
      updatedBy: localStorage.getItem('currentUser') || 'system',
      updatedAt: new Date().toISOString(),
    });
    setErrors({});
    onClose();
  };

  // 如果模态框未打开，则不渲染
  if (!isOpen) return null;

  return (
    <div className="modal-overlay">
      <div className="modal-content">
        <div className="modal-header">
          <h2 className="modal-title">{isEditing ? '编辑成绩记录' : '添加成绩记录'}</h2>
          <button className="modal-close" onClick={handleClose}>&times;</button>
        </div>
        <div className="modal-body">
          <div className="grid grid-cols-2 gap-4 mb-4">
            <div className="form-group">
              <label htmlFor="term">教学周期 *</label>
              <select
                id="term"
                name="term"
                value={formData.term}
                onChange={handleInputChange}
              >
                <option value="">请选择教学周期</option>
                {termOptions.map(option => (
                  <option key={option.value} value={option.label}>
                    {option.label}
                  </option>
                ))}
              </select>
              {errors.term && <div className="form-error">{errors.term}</div>}
            </div>
            
            <div className="form-group">
              <label htmlFor="examType">类型 *</label>
              <select
                id="examType"
                name="examType"
                value={formData.examType}
                onChange={handleInputChange}
              >
                <option value="">请选择类型</option>
                {examTypeOptions.map(option => (
                  <option key={option.value} value={option.label}>
                    {option.label}
                  </option>
                ))}
              </select>
              {errors.examType && <div className="form-error">{errors.examType}</div>}
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4 mb-4">
            <div className="form-group">
              <label htmlFor="academy">学院 *</label>
              <select
                id="academy"
                name="academy"
                value={formData.academy}
                onChange={handleInputChange}
              >
                <option value="">请选择学院</option>
                {academyOptions.map(option => (
                  <option key={option.value} value={option.label}>
                    {option.label}
                  </option>
                ))}
              </select>
              {errors.academy && <div className="form-error">{errors.academy}</div>}
            </div>
            
            <div className="form-group">
              <label htmlFor="className">班级 *</label>
              <select
                id="className"
                name="className"
                value={formData.className}
                onChange={handleInputChange}
              >
                <option value="">请选择班级</option>
                {classOptions.map(option => (
                  <option key={option.value} value={option.label}>
                    {option.label}
                  </option>
                ))}
              </select>
              {errors.className && <div className="form-error">{errors.className}</div>}
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4 mb-4">
            <div className="form-group">
              <label htmlFor="instructor">导员 *</label>
              <select
                id="instructor"
                name="instructor"
                value={formData.instructor}
                onChange={handleInputChange}
              >
                <option value="">请选择导员</option>
                {instructorOptions.map(option => (
                  <option key={option.value} value={option.label}>
                    {option.label}
                  </option>
                ))}
              </select>
              {errors.instructor && <div className="form-error">{errors.instructor}</div>}
            </div>
            
            <div className="form-group">
              <label htmlFor="lecturer">讲师 *</label>
              <select
                id="lecturer"
                name="lecturer"
                value={formData.lecturer}
                onChange={handleInputChange}
              >
                <option value="">请选择讲师</option>
                {lecturerOptions.map(option => (
                  <option key={option.value} value={option.label}>
                    {option.label}
                  </option>
                ))}
              </select>
              {errors.lecturer && <div className="form-error">{errors.lecturer}</div>}
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4 mb-4">
            <div className="form-group">
              <label htmlFor="teachingMonth">教学月度 *</label>
              <select
                id="teachingMonth"
                name="teachingMonth"
                value={formData.teachingMonth}
                onChange={handleInputChange}
              >
                <option value="">请选择教学月度</option>
                {teachingMonthOptions.map(option => (
                  <option key={option.value} value={option.label}>
                    {option.label}
                  </option>
                ))}
              </select>
              {errors.teachingMonth && <div className="form-error">{errors.teachingMonth}</div>}
            </div>
            
            <div className="form-group">
              <label htmlFor="totalStudents">总人数 *</label>
              <input
                type="number"
                id="totalStudents"
                name="totalStudents"
                value={formData.totalStudents}
                onChange={handleInputChange}
                min="1"
              />
              {errors.totalStudents && <div className="form-error">{errors.totalStudents}</div>}
            </div>
          </div>

          <div className="form-group">
            <label htmlFor="studentId">学生 *</label>
            <select
              id="studentId"
              name="studentId"
              value={formData.studentId}
              onChange={handleInputChange}
            >
              <option value="">请选择学生</option>
              {studentOptions.map(student => (
                <option key={student.value} value={student.value}>
                  {student.label} (ID: {student.value})
                </option>
              ))}
            </select>
            {errors.studentId && <div className="form-error">{errors.studentId}</div>}
          </div>

          {formData.studentName && (
            <div className="form-group">
              <label>学生姓名</label>
              <input
                type="text"
                value={formData.studentName}
                readOnly
                style={{ backgroundColor: '#f5f5f5', cursor: 'not-allowed' }}
              />
            </div>
          )}

          <div className="form-group">
            <label htmlFor="subject">课程 *</label>
            <select
              id="subject"
              name="subject"
              value={formData.subject}
              onChange={handleInputChange}
            >
              <option value="">请选择课程</option>
              {subjectOptions.map(subject => (
                <option key={subject.value} value={subject.label}>
                  {subject.label} (满分: {subject.maxScore})
                </option>
              ))}
            </select>
            {errors.subject && <div className="form-error">{errors.subject}</div>}
          </div>

          <div className="form-group">
            <label htmlFor="score">分数 *</label>
            <input
              type="number"
              id="score"
              name="score"
              value={formData.score}
              onChange={handleInputChange}
              min="0"
              step="0.5"
            />
            {errors.score && <div className="form-error">{errors.score}</div>}
          </div>

          <div className="form-group">
            <label htmlFor="remark">备注（自动生成）</label>
            <textarea
              id="remark"
              name="remark"
              value={autoGenerateRemark(formData.score, formData.subject)}
              readOnly
              style={{ backgroundColor: '#f5f5f5', cursor: 'not-allowed' }}
              rows={2}
            />
          </div>
        </div>
        <div className="modal-footer">
          <button className="btn-secondary" onClick={handleClose}>取消</button>
          <button className="btn-primary" onClick={handleSave}>
            {isEditing ? '更新' : '保存'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default AddEditGradeModal;